/*
 * @Author: 码农 2646995216@qq.com
 * @Date: 2025-02-17 21:10:54
 * @LastEditors: 码农 2646995216@qq.com
 * @LastEditTime: 2025-02-17 21:24:22
 * @FilePath: /CH1/pipe/text.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>


void writeer(int wir)
{
    const char* str="I am father";
    char buffer[100];
    int count=0;
    while (1)
    {
         snprintf(buffer, sizeof(buffer), "%s:%d\n", str, count);
         write(wir, buffer, strlen(buffer)-1);
         count++;
         sleep(1);
    }
    
}

void reader(int rea)
{
    char buffer[100];
    while(1)
    {
        size_t n=read(rea,buffer,sizeof(buffer)-1);
        printf("%s\n",buffer);
    }

}

int main()
{
    //开辟管道
    int pipefd[2];
    int n=pipe(pipefd);
    // pipefd[0]-->read   pipefd[1]-->write  0是写端，1是读端
    if(n<0)return 1;
   
    pid_t id=fork();
    if(id==0)//子进程
    {
        close(pipefd[0]);//子进程关闭写通道
        writeer(pipefd[1]);
        exit(0);
    }
    
    close(pipefd[1]);//父进程关闭都通道
    
    reader(pipefd[0]);
    wait(NULL);//回收子进程
    return 0;
}